package cn.pzhu.javaee.mybook.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.pzhu.javaee.mybook.context.MybookConstant;

/**
 * Servlet Filter implementation class AuthFilter
 */
@WebFilter("/mybook")
public class AuthFilter implements Filter {
	private final static Logger log=LoggerFactory.getLogger(AuthFilter.class);
    public AuthFilter() {
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) rsp;
		String url=request.getRequestURL().toString();
		log.debug("Request:"+url);
		HttpSession session=request.getSession();
		if(session.getAttribute(MybookConstant.SESSION_NAME_CUR_USER)!=null){
			chain.doFilter(req, rsp);
		}else{
			String loginUrl=request.getContextPath()+"/login.jsp";
			response.sendRedirect(loginUrl);
		}
		
	}
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
